package sam.learn.framework.dynamicDataSource;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.aop.DynamicDataSourceAnnotationAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import sam.learn.biz.user.service.UserInfoService;
import sam.learn.framework.security.CurrentUser;

@Configuration
public class DynamicDataSourceAdvisorConfig {

    /**
     * AOP切面，对DS注解过的方法进行增强，达到切换数据源的目的
     *
     * @return advisor
     */
    @Bean
    public DynamicDataSourceAnnotationAdvisor dynamicDatasourceAnnotationAdvisor(
            CurrentUser currentUser, UserInfoService userInfoService, DynamicRoutingDataSource dynamicRoutingDataSource, DbDynamicDataSourceLoader dbDynamicDataSourceLoader
    ) {
        DynamicDataSourceAnnotationInterceptor interceptor = new DynamicDataSourceAnnotationInterceptor(currentUser, userInfoService, dynamicRoutingDataSource, dbDynamicDataSourceLoader);
        DynamicDataSourceAnnotationAdvisor advisor = new DynamicDataSourceAnnotationAdvisor(interceptor, DS.class);
        advisor.setOrder(Ordered.LOWEST_PRECEDENCE);
        return advisor;
    }


}
